# -*- coding: utf-8 -*-
import os
import yaml

HEADER = r'G:\django-codes\AutoCreateCase\testHeader'
CONTENT = r'G:\django-codes\AutoCreateCase\testContent'
ROOT = r'G:\django-codes\AutoCreateCase'
TEST_CASE = r'G:\django-codes\AutoCreateCase\channel_add.yaml'


class CreateCase(object):

    def __init__(self):
        self.header = None
        self.content = None

    def __enter__(self):
        self.header = open(HEADER, encoding='utf-8')
        self.head = self.header.read()
        self.content = open(CONTENT, encoding='utf-8')
        self.cont = self.content.read()
        return self

    def make_header_and_content(self, class_name, func):
        filename = ROOT + '\\' + class_name + '.py'
        if not os.path.exists(filename):
            with open(filename, 'w', encoding='utf-8') as file:
                file.write(self.head.format(class_name, class_name))

        with open(filename, 'a') as file:
            file.write(self.cont.format(func))

    def make_case_templates(self):
        class_name = str(os.path.basename(TEST_CASE).split('.')[0].title()).replace('_', '')
        with open(TEST_CASE,  encoding='utf-8') as file:
            for items in yaml.load(file):
                for func, body in items.items():
                    yield {
                        'class_name': class_name,
                        'func_name': func,
                        'body': body
                    }, self.make_header_and_content

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.header.close()
        self.content.close()
        del self.head
        del self.cont


class CaseContainer:

    cases = []

    with CreateCase() as file:
        for items in file.make_case_templates():
            obj, func = items
            func(
                obj['class_name'],
                obj['func_name'],
            )
            cases.append(obj)

    def __iter__(self):
        return iter(self.cases)

    def __next__(self):
        return next(self.cases)
